define(function(require, exports, module) {
    require('basic');
    require('jquerytmpl');
    require('switch');
    var config = require('config');
    var user = require('user');
    var data_str = user.info.leadPost;

    var model = function(){
        this.init();
        this.postData = {}
    };

    model.prototype ={
        init: function(){
            this.addEvents();
        },
        
        /**
         * [checkAll 全选动作]
         * @param  {[jqobj]} _wrap [description]
         * @return {[type]}       [description]
         */
        checkAll: function(_wrap){
            _wrap.find('input.checked_all').each(function(){
                $(this).removeAttr('checked');
                $(this).change(function(e) {
                    var bl = $(this).prop('checked');
                    _wrap.find('input.form_checkbox').prop({checked:bl});
                });
            });
        },
        /**
         * [getElement 获取当前步骤的blok和wrap]
         * @param  {[type]} a [上一步]
         * @param  {[type]} b [当前]
         * @param  {[type]} c [下一步]
         * @return {[type]}   [两个步骤的block和wrap]
         */
        getElement: function(a,b,c){
            var sf = this,
                items = {};
            if(a){
                items.prev = a;
                items.prevBlock = sf.objSteps[a];
            };
            if(b){
                items.now = b;
                items.nowBlock = sf.objSteps[b];
                items.wrap = items.nowBlock.find('table.table-list tbody');
            };
            if(c){
                items.next = c;
                items.nextBlock = sf.objSteps[c];
            };
            return items;
        },
        /**
         * [show_step_1,显示第step_1]
         */
        show_step_1: function(){
            var sf = this,
                step_data = step_data ? step_data : {},
                items = this.getElement('','step_1','step_2');
            items.nowBlock.show();
            var viewObj = {
                pool_select: $('#form_proj_pool')
            };
            var getPoolAjax = $.ajax({
                type: "GET",
                url: config.pool_list+data_str,
                dataType: 'json',
                success: function(data){//get pool池
                    viewObj.pool_select.html('');
                    for(var i=0;i<data.length;i++){
                        var opt = $('<option data-index="'+i+'" value="'+data[i]['pool_id']+'">'+data[i]['name']+'</option>');
                        opt.appendTo(viewObj.pool_select);
                    };
                } 
            });
            items.nowBlock.find('button.next').off('click').on('click',function(){//下一步button的click事件，以及检查提交的.form-control
                var step_bl = true;
                items.nowBlock.find('.form-control').each(function(index,el){
                    if($(el).val()){
                        $(el).removeClass('error');
                        step_data[$(el).attr('name')] = $(el).val();
                        if($(el).attr('name') == 'form_proj_pool'){
                            step_data['form_proj_pool_name'] = $(el).find('option:selected').text();
                        };
                    }else{
                        if(index==1 || index==2 || index==4){//index为1，2，4的.form-control不是必填参数
                            step_data[$(el).attr('name')] = '';
                        }else{
                            $(el).addClass('error');
                            step_bl = false;
                        };
                    };
                });
                if(step_bl){
                    sf.step_1_data = step_data;
                    items.nowBlock.hide();
                    sf.show_step_2();
                };
            });
        },
        /**
         * [show_step_2,显示第step_2]
         */
        show_step_2: function(){
            var sf = this,
                items = this.getElement('step_1','step_2','step_3');
            this.step_2_index = this.step_2_index>0 ? this.step_2_index : 0;
            items.nowBlock.show();

            items.nowBlock.find('button.next').off('click').on('click',function(){//下一步button的click事件，以及检查提交的.form-control
                var step_bl = true;
                var step_data = step_data ? step_data : [];
                items.wrap.find('tr').each(function(index,item){
                    step_data[index] = [];
                    $(item).find('.form-control').each(function(ind,el){
                        if($(el).val()){
                            $(el).removeClass('error');
                            if($(el).attr('type') == 'checkbox'){
                                step_data[index][ind] = $(el).prop('checked');
                            }else if($(el).attr('type') == 'number'){
                                step_data[index][ind] = $(el).val()*1;
                            }else{
                                step_data[index][ind] = $(el).val();
                            };
                        }else{
                            step_data[index][ind] = null;
                            $(el).addClass('error');
                            step_bl = false;
                        };
                    });
                });
                if(step_bl && step_data.length !=0){
                    sf.step_2_data = step_data;
                    items.nowBlock.hide();
                    sf.show_step_3();
                }else{
                    if(step_data.length==0){
                        alert('请添加服务规划');
                    };
                };
            });
            items.nowBlock.find('button.prev').off('click').on('click',function(){
                items.nowBlock.hide();
                sf.show_step_1();
            });
            function addStepList(num){ //在tbody里面加入各行<tr>
                var str = "form_control_"+num;
                var data = {};
                for(var i=0;i<8;i++){
                    data['name_'+i] = str+'_'+i;
                };
                var tr = $('#step2ListTemplate').tmpl(data).appendTo(items.wrap);
                var opt_index =0;
                function optFN(obj){ //在以一个select框加入option，关联第二个select框option和设置服务标记的value
                    var opt = $('<option>'+obj.service+'</option>'),
                        text = tr.find('input:text').eq(0),
                        select = tr.find('select').eq(0),
                        select_1 = tr.find('select').eq(1);
                    opt.appendTo(select);
                    function slectChange(){
                        text.val(obj['service']+'-'+$.randomNumber());
                        select_1.html('');
                        var d = obj['items'];
                        for(var i=0;i<d.length;i++){
                            var sub_opt = $('<option>'+d[i]['version']+'</option>');
                            sub_opt.appendTo(select_1);
                        };
                    };
                    select.on('change',function(){
                        if(opt.prop('selected')){//选中第一个select的option，改变第二个select的option
                            slectChange();
                        };
                    });
                    if(opt_index==0){//默认选中第一个option
                        slectChange();
                    };
                    opt_index++;
                };
                $.ajax({
                    type: "GET",
                    url: config.repo_list+data_str,
                    dataType: 'json',
                    success: function(data){//ajax加载repo_list的组件
                        for(var o=0;o<data.length;o++){
                            var d = data[o]['services'];
                            for(var e=0;e<d.length;e++){
                                var opt_obj = d[e];
                                optFN(opt_obj);
                            };
                        };
                        
                    } 
                });
                $('input.form-control[type="checkbox"]').bootstrapSwitch();
                sf.checkAll(items.nowBlock);
                sf.step_2_index++;
            };
            function removeStepList(){//删除tbody里面的<tr>
                $(items.wrap).find('tr').each(function(index,el){
                    var bl = $(el).find('.form_checkbox').prop('checked');
                    if(bl){
                        $(el).remove();
                        sf.step_2_index--;
                    };
                });
            };
            items.nowBlock.find('button#step_2_add_btn').off('click').on('click',function(e){
                addStepList(sf.step_2_index);
            });
            items.nowBlock.find('button#step_2_delete_btn').off('click').on('click',function(e){
                removeStepList();
            });
            if(sf.step_2_index==0){
                addStepList(sf.step_2_index);
            };
        },
        /**
         * [show_step_3,显示第step_3]
         */
        show_step_3: function(){
            var sf = this,
                step_data = step_data ? step_data : {},
                items = this.getElement('step_2','step_3','step_4'),
                level = {
                    top: ['apache','nginx','tonging'],
                    middle: ['wildfly','tomcat'],
                    bottom: ['rabbitmq','activemq','redis','couchbase','mysql']
                },
                relation = {
                    top: [],
                    middle: []
                },
                d = sf.step_2_data, //第二步选择创建的服务标记的数据[["apache-c475", "apache", "2.2.29", 1, true, true, true, true], ["nginx-3589", "nginx", "1.7.10", 1, true, true, true, true], ["mysql-d601", "mysql", "5.5.32", 1, true, true, true, true]]
                data_arr = [];
            items.nowBlock.show();
            for(var i=0;i<d.length;i++){
                data_arr[i] = {};
                data_arr[i]['data'] = d[i]; //["apache-c475", "apache", "2.2.29", 1, true, true, true, true]
                var level_str = d[i][1]; //组件名'apache','nginx','tonging'...
                for(var o in level){
                    if($.inArray(level_str,level[o])>=0){
                        data_arr[i]['level'] = o;
                        if(o!='top'){
                            relation['top'].push(d[i]);
                            if(o!='middle'){
                                relation['middle'].push(d[i]);
                            }else{
                                data_arr[i]['relation'] = relation[o];
                            };
                        }else{
                            data_arr[i]['relation'] = relation[o];
                        };
                    };
                };
            };
            items.wrap.html('');
            var tr = $('#step3ListTemplate').tmpl(data_arr).appendTo(items.wrap);
            for(var a=0;a<data_arr.length;a++){
                if(data_arr[a]['relation']){
                    var rel = data_arr[a]['relation'];
                    for(var e=0;e<rel.length;e++){
                        var label = $('<label class="btn btn-primary"><input value="'+rel[e][0]+'" type="checkbox" autocomplete="off"> '+rel[e][0]+'</label>').appendTo($(items.wrap).find('tr').eq(a).find('.btn-group'));
                    };
                }
                
            };
            items.nowBlock.find('button.next').off('click').on('click',function(){
                $(items.wrap).find('.btn-group').each(function(index,el){
                    data_arr[index]['rel'] = [];
                    var rel = data_arr[index]['relation'];
                    $(el).find('label.active').each(function(ind,item){
                        data_arr[index]['rel'].push(rel[ind]);
                    });
                });
                sf.step_3_data = data_arr;
                items.nowBlock.hide();
                sf.show_step_4();
            });
            items.nowBlock.find('button.prev').off('click').on('click',function(){
                items.nowBlock.hide();
                sf.show_step_2();
            });
        },
        /**
         * [show_step_4,显示第step_4]
         */
        show_step_4: function(){
            var sf = this,
                step_data = step_data ? step_data : {},
                items = this.getElement('step_3','step_4','');
            items.nowBlock.show();
            items.wrap.html('');
            var tr = $('#step4ListTemplate').tmpl(sf.step_3_data).appendTo(items.wrap);
            var d = sf.step_1_data;
            var d1 = sf.step_3_data;
            for(var i in d){
                $('.'+i).text(d[i]);
            };
            var components = [];
            $(items.wrap).find('.rel').each(function(index,el){
                components[index] = {
                  'entry_point': d1[index]['data'][4],
                  'feature': {
                    'auto_healing': d1[index]['data'][5],
                    'auto_scaling': d1[index]['data'][6],
                    'high_available': d1[index]['data'][7]
                  },
                  'link_to': [],
                  'name': d1[index]['data'][0],
                  'node_num': d1[index]['data'][3],
                  'image_name': d1[index]['data'][1],
                  'version': d1[index]['data'][2]
                };
                $(el).html('');
                var data = d1[index]['rel'];
                for(var o=0;o<data.length;o++){
                    var rel_item = $('<div class="items">'+data[o][0]+'</div>').appendTo(el);
                    components[index]['link_to'].push({'name':data[o][0]})
                };
            });
            items.nowBlock.find('button.next').off('click').on('click',function(){
                var sd_1 = sf.step_1_data,
                    sd_3 = sf.step_3_data;
                var postData = {
                    "code": sd_1["form_proj_number"],
                    "components": components,
                    "name": sd_1["form_proj_name"],
                    "owner": sd_1["form_proj_belong"],
                    "pool": sd_1["form_proj_pool_name"],
                    "remark": sd_1["form_proj_dis"]
                };
                $.ajax({
                    type: "POST",
                    url: config.project_create+data_str,
                    data: JSON.stringify(postData),
                    dataType: 'json',
                    beforeSend: function () {
                        $('.loading').show();
                    },
                    success: function(data){//
                        if(data){
                            $('.loading').hide();
                            $('#alert_pop').modal({keyboard: false, show: true});
                            $('#alert_pop .btn-primary').click(function(e){
                                window.location.href = $(this).attr('href');
                            });
                        }
                    },
                    error: function(e){
                        $('.loading').hide();
                        $('#error_body').html('').html(e.responseText);
                        $('#error').modal({keyboard: false, show: true});
                    }
                });
            });
            items.nowBlock.find('button.prev').off('click').on('click',function(){
                items.nowBlock.hide();
                sf.show_step_3();
            });
        },
        /**
         * [addEvents 各步骤上一步下一步的事件,.done是最后提交按钮]
         */
        addEvents: function(){
            var sf = this;
            this.objSteps = {
                step_1 : $('#step_1'),
                step_2 : $('#step_2'),
                step_3 : $('#step_3'),
                step_4 : $('#step_4')
            };
            this.show_step_1();

            $('.cancel').off('click').on('click',function(){
                $('#alert_pop2').modal({keyboard: false, show: true});
            });
            $('#alert_pop2 .btn-primary').click(function(e){
                window.location.href = $(this).attr('href');
            });
        }
    };

    module.exports = new model();
    
});

